<script setup lang="ts">
import type {
  OnActionClickParams,
  VxeTableGridOptions,
} from '#/adapter/vxe-table';
import type { ProductStateModel } from '#/api/production/models';

import { useVbenModal } from '@vben/common-ui';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getReworkablePagedListApi } from '#/api/rework/reworkDoc';

import { useColumns, useSearchSchema } from './data';
import Form from './modules/form.vue';

const emit = defineEmits<{
  done: [];
}>();

const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: Form,
  destroyOnClose: true,
});

/**
 * 返工
 */
function onRework(row: ProductStateModel) {
  formModalApi.setData(row).open();
}

/**
 * 表格操作按钮的回调函数
 */
function onActionClick({ code, row }: OnActionClickParams<ProductStateModel>) {
  switch (code) {
    case 'rework': {
      onRework(row);
      break;
    }
  }
}

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    collapsed: true,
    schema: useSearchSchema(),
    // 控制表单是否显示折叠按钮
    showCollapseButton: false,
    submitOnEnter: false,
    wrapperClass: 'grid-cols-2',
  },
  gridOptions: {
    columns: useColumns(onActionClick),
    border: true,
    stripe: true,
    pagerConfig: {},
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues) => {
          return await getReworkablePagedListApi({
            pageNumber: page.currentPage,
            pageSize: page.pageSize,
            ...formValues,
          });
        },
      },
    },
  } as VxeTableGridOptions,
});

/**
 * 提交
 */
function onSubmit() {
  refresh();
  emit('done');
}

/**
 * 刷新表格
 */
function refresh() {
  gridApi.query();
}

defineExpose({ refresh });
</script>

<template>
  <div class="h-full w-full">
    <FormModal @success="onSubmit()" />
    <Grid />
  </div>
</template>
